package cn.com.dingtek.genius.manager.server.service;

import cn.com.dingtek.genius.manager.server.repository.db.entity.AuthGroup;
import cn.com.dingtek.genius.manager.server.repository.db.entity.CompanyBase;
import cn.com.dingtek.genius.manager.server.repository.db.entity.StaffBase;
import cn.com.dingtek.genius.manager.server.repository.db.manager.AuthGroupManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.CompanyBaseManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.StaffBaseManager;
import cn.com.dingtek.genius.manager.server.utils.MybatisPlusUtil;
import cn.com.dingtek.genius.manager.server.utils.Verify;
import cn.com.dingtek.genius.manager.server.utils.VerifyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StaffService {
    @Autowired
    private StaffBaseManager staffBaseManager;
    @Autowired
    private CompanyBaseManager companyBaseManager;
    @Autowired
    private AuthGroupManager authGroupManager;


    public JSONObject list(StaffBase param, int currentPage, int pageSize) {
        QueryWrapper<StaffBase> query = Wrappers.emptyWrapper();
        if (param != null) {
            query = MybatisPlusUtil.customEqQuery(null, "company_id", param.getCompanyId());
            query = MybatisPlusUtil.customEqQuery(query, "auth_group_id", param.getAuthGroupId());
            query = MybatisPlusUtil.customEqQuery(query, "account_name", param.getAccountName());
            query = MybatisPlusUtil.customEqQuery(query, "mobile", param.getMobile());

        }

        IPage<StaffBase> staffBasePage = staffBaseManager.page(new Page<StaffBase>(currentPage, pageSize).setDesc("id"), query);

        List<JSONObject> records = staffBasePage.getRecords().stream()
                .map(item -> {
                    JSONObject jsonObject = (JSONObject) JSON.toJSON(item);
                    String authGroupName = "--";

                    if (item.getAuthGroupId() != null) {
                        AuthGroup authGroup = authGroupManager.getById(item.getAuthGroupId());
                        if (authGroup != null) {
                            authGroupName = authGroup.getGroupName();
                        }
                    }

                    String companyName = "--";
                    if (item.getCompanyId() != null) {
                        CompanyBase companyBase = companyBaseManager.getById(item.getCompanyId());
                        if (companyBase != null) {
                            companyName = companyBase.getCompanyName();
                        }
                    }

                    return jsonObject.fluentPut("authGroupName", authGroupName).fluentPut("companyName", companyName);
                }).collect(Collectors.toList());
        return new JSONObject().fluentPut("total", staffBasePage.getTotal())
                .fluentPut("records", records);
    }


    public void add(StaffBase param, Date now) {
        String passwdHash = DigestUtils.md5DigestAsHex(param.getPasswd().getBytes(StandardCharsets.UTF_8));
        try {
            Verify.isTrue(staffBaseManager.save(StaffBase.builder()
                    .accountName(param.getAccountName())
                    .realName(param.getRealName())
                    .passwd(passwdHash)
                    .companyId(param.getCompanyId())
                    .authGroupId(param.getAuthGroupId())
                    .mobile(param.getMobile())
                    .address(param.getAddress())
                    .remark(param.getRemark())
                    .ctime(now)
                    .utime(now).build()), "新增员工失败.");
        } catch (DuplicateKeyException e) {
            throw new VerifyException("该员工账号已存在");
        }
    }

    public StaffBase info(Long id) {
        Verify.isTrue(id != null && id > 0, "员工不存在");
        return staffBaseManager.getById(id);
    }

    public void update(StaffBase param, Date now) {
        Verify.isTrue(param.getId() != null && param.getId() > 0, "员工不存在");

        StaffBase staffBase = staffBaseManager.getById(param.getId());
        Verify.notNull(staffBase, "员工不存在");

        StaffBase toUpdate = StaffBase.builder()
                .id(param.getId())
                .realName(param.getRealName())
                .companyId(param.getCompanyId())
                .authGroupId(param.getAuthGroupId())
                .mobile(param.getMobile())
                .address(param.getAddress())
                .remark(param.getRemark())
                .utime(now)
                .version(staffBase.getVersion()).build();

        Verify.isTrue(staffBaseManager.updateById(toUpdate), "更新员工失败");
    }

    public void remove(Long id) {
        if (id != null && id > 0) {
            staffBaseManager.removeById(id);
        }
    }
}
